package com.temi.demo.net;

import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.Toast;

import com.temi.demo.MyApplication;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by coco on 2018/3/14.
 * <p>
 * 公共操作
 */
public class BaseCallBack<T> implements Callback<T> {
    private CallbackListener<T> listener;

    public BaseCallBack(CallbackListener<T> listener) {
        this.listener = listener;
    }

    @Override
    public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
        T result = response.body();

        if (response.isSuccessful()) {
            if (result != null) {
                // return data
                sendResult(result);
            } else {
                showMsg("no data");
            }

        } else {
            ResponseBody errorBody = response.errorBody();
            if (errorBody != null) {
                showMsg("request exception, try again later");
            }
        }
    }

    @Override
    public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
        String message = t.getMessage();
        if (t instanceof SocketTimeoutException) {
            message = "request timeout";
        } else if (t instanceof ConnectException) {
            message = "connect timeout, try again";
        }

        if (MyApplication.mContext != null) {
            Toast.makeText(MyApplication.mContext, message, Toast.LENGTH_SHORT).show();
        }

        if(listener != null){
            listener.onError();
        }
    }

    /**
     * @param msg 异常提示
     */

    private void showMsg(String msg) {
        if (MyApplication.mContext != null && !TextUtils.isEmpty(msg)) {
            Toast.makeText(MyApplication.mContext, msg, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * @param result 结果回调
     */
    private void sendResult(T result) {
        if (result != null) {
            if (listener != null) {
                listener.onSuccess(result);
            }
        }
    }

    public interface CallbackListener<T> {
        void onSuccess(T result);

        void onError();
    }
}
